package com.javaeedev.junit;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.Context;

public abstract class JmsQueueTemplate {

    public final void sendMessage(Context context, String jndi_factory, String jndi_destination) throws Exception {
        QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup(jndi_factory);
        Queue queue = (Queue) context.lookup(jndi_destination);
        QueueConnection connection = factory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        QueueSender sender = session.createSender(queue);
        Message message = createMessage(session);
        sender.send(message);
        sender.close();
        session.close();
        connection.close();
    }

    protected abstract Message createMessage(QueueSession session) throws JMSException;

    public static Message receiveMessage(Context context, String jndi_factory, String jndi_destination) throws Exception {
        QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup(jndi_factory);
        Queue queue = (Queue) context.lookup(jndi_destination);
        QueueConnection connection = factory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        QueueReceiver receiver = session.createReceiver(queue);
        Message message = receiver.receive(60000);
        receiver.close();
        session.close();
        connection.close();
        return message;
    }
}
